/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import model.Player;
import observer.UpdateNotifier;
import observer.UpdateObserver;
import config.Debug;
import config.Helper;
import config.Settings;
import data.HttpPostConnector;

/**
 * 
 * @author Yang Wang <yang@digitalmenubox.com>
 */
public class UpdateChecker implements UpdateNotifier, Runnable {
	private static boolean needToDownloadContent = false;
	private List<UpdateObserver> observers = new ArrayList<UpdateObserver>();

	public UpdateChecker() {
		// this.registerUpdateNotifier(Player.getInstance());
		// this.registerUpdateNotifier(AdminFrame.getInstance());
	}

	public static boolean hasNewUpdate() {
		try {
			URL url = new URL(Settings.UPDATE_CHECKER_URL);
			String data = HttpPostConnector.getBoxToken() + "&reqtype=checkupdate";
			HttpPostConnector conn = new HttpPostConnector(url, data);
			conn.post();
			if (conn.getResult() != null && conn.getResult().contains("true")) {
				return true;
			} else {
				// System.out.println("Get Update Result: " + conn.getResult());
			}
		} catch (MalformedURLException ex) {
			Logger.getLogger(UpdateChecker.class.getName()).log(Level.SEVERE, null, ex);
		}
		return false;
	}

	@Override
	public void run() {
		boolean notUpdated = true;
		while (notUpdated) {
			Debug.msg("checking update");
			// Debug.log("checking update", Debug.SYSTEM_LEVEL);
			if (Helper.hasNetworkConnection() && UpdateChecker.hasNewUpdate()) {
				/* Download the update file using ftp or http */
				Initializer.downloadUpdate(false);
				Initializer.executeSqlScriptsFromFolder();
				Initializer.inputCsvFilesToDatabase();
				Player.getInstance().update();
				Initializer.downloadContents();
				Initializer.runCommandLineScripts();
				Command.upgradePlayer();
				Debug.log("The player has received new updates.", Debug.SYSTEM_LEVEL);
			} else if (needToDownloadContent) {
				boolean result = Initializer.downloadContents();
				needToDownloadContent = !result;
			} else {

			}
			// wait sometime before the next iteration
			try {
				Thread.sleep(Settings.getUpdateCheckerFrequency()*1000);
			} catch (InterruptedException ex) {
				Debug.log("UpdateChecker: Interrupted Exception", Debug.EXCEPTION_LEVEL);
			}
		}
	}

	public static void setNeedDownloadContent(boolean needed) {
		UpdateChecker.needToDownloadContent = needed;
	}

	public static void main(String[] args) {
		Thread t = new Thread(new UpdateChecker());
		t.start();
	}

	@Override
	public void registerUpdateNotifier(UpdateObserver o) {
		if (!this.observers.contains(o)) {
			observers.add(o);
		}
	}

	@Override
	public void removeUpdateNotifier(UpdateObserver o) {
		if (this.observers.contains(o)) {
			observers.remove(o);
		}
	}

	@Override
	public void notifyUpdateObservers() {
		for (UpdateObserver o : observers) {
			o.updateChanges();
		}
	}
}
